<template>
  <div class="chat-container">
    <!-- 侧边栏（可调整大小） -->
    <div class="sidebar" :style="{ width: store.sidebarWidth + 'px' }">
      <SessionList
        :sessions="sessions"
        :current-session="currentSession"
        @select="handleSelectSession"
        @delete="handleDeleteSession"
        @create="handleCreateSession"
      />
      
      <div class="user-info">
        <div class="user-actions">
          <button class="action-btn secondary" @click="handleClearHistory">
            🗑️ 清空当前会话
          </button>
          <button class="action-btn danger" @click="handleLogout">
            🚪 退出登录
          </button>
        </div>
      </div>
      
      <!-- 调整大小的拖拽条 -->
      <div 
        class="resize-handle"
        @mousedown="startResize"
        title="拖拽调整宽度"
      ></div>
    </div>
    
    <!-- 聊天区域 -->
    <div class="chat-area">
      <div class="chat-header">
        <div class="header-content">
          <h1>✨ DeepSeek-KAI</h1>
          <div class="session-info">
            <span class="session-badge">{{ getSessionTitle() }}</span>
            <span class="message-count-badge" v-if="messages.length > 0">
              {{ messages.length }} 条消息
            </span>
          </div>
        </div>
      </div>
      
      <div v-if="error" class="error-message">
        <span>⚠️</span>
        <span>{{ error }}</span>
      </div>
      
      <div class="messages-container" ref="messagesContainerRef">
        <div v-if="messages.length === 0" class="empty-state">
          <div class="empty-icon">💬</div>
          <h2>开始新的对话</h2>
          <p>输入消息开始与 DeepSeek-KAI 聊天</p>
          <div class="empty-hints">
            <div class="hint-item">💡 支持工作流模式深度分析</div>
            <div class="hint-item">🔧 可调用多个分析工具</div>
            <div class="hint-item">📊 自动生成分析报告</div>
          </div>
        </div>
        
        <ChatMessage
          v-for="msg in messages"
          :key="msg.id"
          :is-user="msg.isUser"
          :content="msg.content"
          :timestamp="msg.timestamp"
          :message-id="msg.id"
          :metadata="msg.metadata"
          @edit="handleEditMessage"
          @copy="handleCopyMessage"
        />
        
        <div v-if="loading" class="loading-indicator">
          <div class="loading-spinner"></div>
          <p>DeepSeek-KAI 正在思考...</p>
        </div>
      </div>
      
      <ChatInput
        :loading="loading"
        @send="handleSendMessage"
      />
    </div>
    
    <!-- 编辑消息对话框 -->
    <EditMessageDialog
      :visible="showEditDialog"
      :content="editOriginalContent"
      @confirm="handleConfirmEdit"
      @cancel="handleCancelEdit"
    />
  </div>
</template>

<script setup>
import { onMounted, computed, ref, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from '../store';
import api from '../api';
import SessionList from '../components/SessionList.vue';
import ChatMessage from '../components/ChatMessage.vue';
import ChatInput from '../components/ChatInput.vue';
import EditMessageDialog from '../components/EditMessageDialog.vue';

const store = useStore();
const router = useRouter();

// Refs
const messagesContainerRef = ref(null);
const isResizing = ref(false);
const showEditDialog = ref(false);
const editMessageId = ref(null);
const editOriginalContent = ref('');

// 计算属性
const sessions = computed(() => store.sessions);
const currentSession = computed(() => store.currentSession);
const messages = computed(() => store.messages[currentSession.value] || []);
const loading = computed(() => store.loading);
const error = computed(() => store.error);

// 获取会话标题
const getSessionTitle = () => {
  return store.sessionInfo[currentSession.value]?.title || currentSession.value;
};

// 初始化加载历史记录
const loadHistory = async (sessionId) => {
  try {
    store.setLoading(true);
    const response = await api.getHistory(sessionId);
    
    // 加载历史记录到store
    store.loadHistory(sessionId, response.data.history);
    
    // 确保历史记录已加载到界面
    await nextTick();
    scrollToBottom();
  } catch (err) {
    console.error('加载历史记录失败:', err);
    store.setError(err.response?.data?.error || '加载历史记录失败');
  } finally {
    store.setLoading(false);
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainerRef.value) {
    nextTick(() => {
      messagesContainerRef.value.scrollTop = messagesContainerRef.value.scrollHeight;
    });
  }
};

// 监听消息变化，自动滚动
watch(() => messages.value.length, () => {
  scrollToBottom();
});

// 挂载时加载当前会话历史
onMounted(() => {
  loadHistory(currentSession.value);
});

// 处理选择会话
const handleSelectSession = async (sessionId) => {
  store.setCurrentSession(sessionId);
  await loadHistory(sessionId);
};

// 处理删除会话
const handleDeleteSession = async (sessionId) => {
  try {
    await api.clearHistory(sessionId);
    store.removeSession(sessionId);
    store.clearSessionMessages(sessionId);
    
    // 删除会话信息
    if (store.sessionInfo[sessionId]) {
      delete store.sessionInfo[sessionId];
      store.saveSessionInfo();
    }
  } catch (err) {
    store.setError(err.response?.data?.error || '删除会话失败');
  }
};

// 处理创建会话
const handleCreateSession = () => {
  // store.addSession() 已经在SessionList中调用
  store.clearSessionMessages(store.currentSession);
};

// 处理发送消息
const handleSendMessage = async (content, useWorkflow = false) => {
  // 添加用户消息到界面
  store.addMessage(currentSession.value, true, content);
  
  try {
    store.setLoading(true);
    
    // 根据工作流模式选择API
    let response;
    if (useWorkflow) {
      response = await api.chatWithWorkflow(currentSession.value, content);
    } else {
      response = await api.chat(currentSession.value, content);
    }
    
    // 构建元数据（工作流信息，包含思维链详情）
    const metadata = response.data.use_workflow ? {
      use_workflow: true,
      tools_used: response.data.tools_used || [],
      workflow_steps: response.data.workflow_steps || 0,
      tool_calls: response.data.tool_calls || [],  // 完整的工具调用详情（包含thought）
      retrieved_logs_count: response.data.retrieved_logs_count || 0
    } : null;
    
    // 添加机器人回复到界面（包含元数据）
    store.addMessage(currentSession.value, false, response.data.reply, metadata);
    
    // 滚动到底部
    scrollToBottom();
  } catch (err) {
    store.setError(err.response?.data?.error || '发送消息失败');
  } finally {
    store.setLoading(false);
  }
};

// 处理编辑消息（打开对话框）
const handleEditMessage = (messageId, originalContent) => {
  const message = store.getMessageById(currentSession.value, messageId);
  if (!message || !message.isUser) return;
  
  editMessageId.value = messageId;
  editOriginalContent.value = originalContent;
  showEditDialog.value = true;
};

// 确认编辑消息
const handleConfirmEdit = async (newContent) => {
  if (!editMessageId.value || !newContent.trim()) {
    showEditDialog.value = false;
    return;
  }
  
  // 关闭对话框
  showEditDialog.value = false;
  
  // 1. 更新消息内容
  store.updateMessage(currentSession.value, editMessageId.value, newContent);
  
  // 2. 删除该消息后的所有消息（包括AI回复）
  store.removeMessagesAfter(currentSession.value, editMessageId.value);
  
  // 3. 重新发送消息生成回复
    try {
    store.setLoading(true);
    
    // 获取当前的工作流设置
    const useWorkflow = store.useWorkflow;
    
    // 根据工作流模式选择API
    let response;
    if (useWorkflow) {
      response = await api.chatWithWorkflow(currentSession.value, newContent);
    } else {
      response = await api.chat(currentSession.value, newContent);
    }
    
    // 构建元数据
    const metadata = response.data.use_workflow ? {
      use_workflow: true,
      tools_used: response.data.tools_used || [],
      workflow_steps: response.data.workflow_steps || 0,
      tool_calls: response.data.tool_calls || [],
      retrieved_logs_count: response.data.retrieved_logs_count || 0
    } : null;
    
    // 添加机器人回复到界面
    store.addMessage(currentSession.value, false, response.data.reply, metadata);
    
    // 滚动到底部
    scrollToBottom();
    
    // 重置编辑状态
    editMessageId.value = null;
    editOriginalContent.value = '';
  } catch (err) {
    store.setError(err.response?.data?.error || '重新生成回复失败');
  } finally {
    store.setLoading(false);
  }
};

// 取消编辑
const handleCancelEdit = () => {
  showEditDialog.value = false;
  editMessageId.value = null;
  editOriginalContent.value = '';
};

// 处理复制消息
const handleCopyMessage = () => {
  // 可以添加一个简单的提示
  // 实际复制操作已在ChatMessage组件中完成
};

// 处理清空历史
const handleClearHistory = async () => {
  if (confirm(`确定要清空当前会话 "${getSessionTitle()}" 的历史记录吗？`)) {
    try {
      await api.clearHistory(currentSession.value);
      store.clearSessionMessages(currentSession.value);
      store.updateSessionInfo(currentSession.value, { lastMessage: '' });
    } catch (err) {
      store.setError(err.response?.data?.error || '清空历史记录失败');
    }
  }
};

// 处理退出登录
const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    store.clearApiKey();
    router.push('/login');
  }
};

// 调整侧边栏大小（优化性能）
const startResize = (e) => {
  e.preventDefault();
  isResizing.value = true;
  const startX = e.pageX;
  const startWidth = store.sidebarWidth;
  
  let rafId = null;
  let pendingWidth = startWidth;
  
  // 使用 requestAnimationFrame 优化性能
  const updateWidth = () => {
    // 使用store方法但不保存到localStorage，提高性能
    store.setSidebarWidth(pendingWidth, false);
    rafId = null;
  };
  
  const doResize = (e) => {
    const diff = e.pageX - startX;
    const newWidth = Math.max(200, Math.min(600, startWidth + diff));
    
    // 只更新pendingWidth，不立即写入store
    pendingWidth = newWidth;
    
    // 使用requestAnimationFrame批量更新，避免频繁写入
    if (rafId === null) {
      rafId = requestAnimationFrame(updateWidth);
    }
  };
  
  const stopResize = () => {
    isResizing.value = false;
    
    // 确保最后一次更新
    if (rafId !== null) {
      cancelAnimationFrame(rafId);
    }
    store.setSidebarWidth(pendingWidth);
    
    document.removeEventListener('mousemove', doResize);
    document.removeEventListener('mouseup', stopResize);
    document.body.style.cursor = '';
    document.body.style.userSelect = '';
  };
  
  // 防止选中文本
  document.body.style.cursor = 'col-resize';
  document.body.style.userSelect = 'none';
  
  document.addEventListener('mousemove', doResize);
  document.addEventListener('mouseup', stopResize);
};
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background: #f5f7fa;
  overflow: hidden;
}

.sidebar {
  position: relative;
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
  border-right: 1px solid rgba(0, 0, 0, 0.08);
  box-shadow: 2px 0 12px rgba(0, 0, 0, 0.05);
  min-width: 200px;
  max-width: 600px;
  /* 移除transition，提高拖拽响应速度 */
  /* transition: width 0.2s ease; */
}

.resize-handle {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  cursor: col-resize;
  background: transparent;
  z-index: 10;
}

.resize-handle:hover {
  background: rgba(102, 126, 234, 0.3);
}

.resize-handle::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 2px;
  height: 40px;
  background: rgba(102, 126, 234, 0.5);
  border-radius: 2px;
  opacity: 0;
  transition: opacity 0.2s;
}

.resize-handle:hover::after {
  opacity: 1;
}

.user-info {
  padding: 1rem 1.25rem;
  border-top: 1px solid rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.8);
}

.user-actions {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.action-btn {
  padding: 0.75rem 1rem;
  border-radius: 8px;
  border: none;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn.secondary {
  background: #f0f0f0;
  color: #333;
}

.action-btn.secondary:hover {
  background: #e0e0e0;
  transform: translateY(-1px);
}

.action-btn.danger {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
  color: white;
}

.action-btn.danger:hover {
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
  transform: translateY(-1px);
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  overflow: hidden;
}

.chat-header {
  padding: 1.25rem 2rem;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h1 {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
}

.session-info {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}

.session-badge {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0.4rem 1rem;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.message-count-badge {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  padding: 0.4rem 0.75rem;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
}

.messages-container {
  flex: 1;
  padding: 2rem 2rem 2rem 2.5rem;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  scroll-behavior: smooth;
}

.messages-container::-webkit-scrollbar {
  width: 8px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: rgba(102, 126, 234, 0.3);
  border-radius: 4px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: rgba(102, 126, 234, 0.5);
}

.empty-state {
  margin: auto;
  text-align: center;
  padding: 3rem;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  max-width: 500px;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-state h2 {
  color: #2c3e50;
  margin: 0.5rem 0;
  font-size: 1.5rem;
}

.empty-state p {
  color: #666;
  margin: 0.5rem 0 2rem 0;
}

.empty-hints {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-top: 2rem;
}

.hint-item {
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
  padding: 0.75rem 1rem;
  border-radius: 10px;
  color: #4a90e2;
  font-size: 0.9rem;
  text-align: left;
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin: 1.5rem auto;
  padding: 1rem 1.5rem;
  background: white;
  border-radius: 12px;
  color: #666;
  font-size: 0.95rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 3px solid rgba(102, 126, 234, 0.2);
  border-top-color: #667eea;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
  color: white;
  padding: 1rem 1.5rem;
  margin: 1rem 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
  animation: shake 0.5s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-10px); }
  75% { transform: translateX(10px); }
}
</style>
